package com.emm.yixun.website.controller.estate;
//框架包
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
//common
import com.emm.yixun.common.page.PageUtil;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.BeanUtil;
import com.emm.yixun.common.model.Project;
import com.emm.yixun.common.model.ProjectImg;
import com.emm.yixun.common.model.Resources;
import com.emm.yixun.common.model.User;
//website
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.utils.base.Const;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.controller.base.BaseController;
import com.emm.yixun.website.vo.estate.ProjectHouseTypeVo;
//变化的引用
import com.emm.yixun.common.model.ProjectHouseType;
import com.emm.yixun.common.model.dto.ProjectHouseTypeDto;
import com.emm.yixun.common.model.dto.ProjectImgDto;
import com.emm.yixun.common.model.enums.PositionEnum;
import com.emm.yixun.estate.service.ProjectHouseTypeServiceFacade;
import com.emm.yixun.estate.service.ProjectImgServiceFacade;
import com.emm.yixun.estate.service.ProjectServiceFacade;
@Controller
@RequestMapping("/estate/projectHouseType/")
public class ProjectHouseTypeController extends BaseController<ProjectHouseType>{
	
	@Autowired
	private ProjectHouseTypeServiceFacade projectHouseTypeServiceFacade;
	
	@Autowired
	private ProjectServiceFacade projectServiceFacade;
	
	@Autowired
	private ProjectImgServiceFacade projectImgServiceFacade;
	
	@RequestMapping(value="index")
	public String index(ModelMap map,Long projectId){
		 if(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"estate:projectHouseType:list")){
			Response<Project> response=projectServiceFacade.findById(projectId);
			if(response.isSuccess()){
				map.put("project", response.getEntity());
			}else{
				map.put("project", new Project());
			}
			//查询菜单按钮权限
			List<Resources> resources= getPermitBtn(Const.RESOURCES_TYPE_FUNCTION);
			map.put("permitBtn", resources);	
			map.put("permitBtnList", JSONArray.fromObject(resources));
			return "/estate/projectHouseType/pht_list";
		}
		return Const.NO_AUTHORIZED_URL;
	}
	@RequestMapping(value="toAdd")
	public String toAdd(ModelMap map,String projectId){
		map.put("positionEnum", PositionEnum.values());
		map.put("projectId", projectId);
		return "/estate/projectHouseType/form";
	}
	
	//新增返回实体对象
	@RequestMapping(value="add", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  add(ProjectHouseTypeDto dto,HttpServletRequest request,String houseTypeUrls){
    	AjaxRes ar=getAjaxRes();
    	
    	/*
    	 *1.判断权限 
    	 *2.调用新增接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"estate:projectHouseType:add"))){
        	try {
        		String[] positionCheck=request.getParameterValues("positionCheck");
        		User user=ShiroUtil.getCurrentUser();
        		Response<Project> responseProject=projectServiceFacade.findById(dto.getProjectId());
    			if(responseProject.isSuccess()){
    				dto.setProjectCode(responseProject.getEntity().getProjectCode());
    				dto.setAccessCode(responseProject.getEntity().getProjectCode());
    			}
    			String position="";
    			if(null != positionCheck && positionCheck.length > 0) {
    				for(int i=0;i<positionCheck.length;i++){
        				if(i==0){
        					position=positionCheck[i];
        				}else{
        					position=","+positionCheck[i];
        				}
        			}
    			}
        		dto.setPosition(position);
        		dto.setUserCode(user.getUserCode());
        		dto.setMerchantId(user.getMerchantId());
        		dto.setCreateUserId(user.getId());
        		dto.setDelFlag("0");
        		dto.setUpdateUserId(user.getId());
        		dto.setUpdateTime(new Date());
				Response<ProjectHouseTypeDto> response=projectHouseTypeServiceFacade.save(dto);
				if(response.isSuccess()){
					saveProjectImg(user,response.getEntity(),houseTypeUrls);
					ar.setSucceedMsg(Const.SAVE_SUCCEED);
				}else{
					ar.setFailMsg(Const.SAVE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.SAVE_FAIL);
			}
    	}
    	return ar;
    }
	
	private void saveProjectImg(User user,ProjectHouseTypeDto projectHouseTypeDto,String houseTypeUrls){
		if(null==projectHouseTypeDto)return;
		//删除这个项目下面所有的图片
		if(projectHouseTypeDto.getId()!=null){
			ProjectImgDto dto = new ProjectImgDto();
			dto.setProjectId(projectHouseTypeDto.getId());
			dto.setProjectImgType("20");
			dto.setProjectImgCode("houseTypeCode");
			ResponseList<ProjectImg> list = projectImgServiceFacade.findByDto(dto);
			if(list.isSuccess()&&list.getEntity()!=null){
				for (ProjectImg img:list.getEntity()) {
					projectImgServiceFacade.deleteByPrimaryKey(img.getId());
				}
			}
		}
		Long projectHouseTypeId=projectHouseTypeDto.getId();
		String projectCode=projectHouseTypeDto.getProjectCode();
		//保存户型图片
		if(StringUtils.isBlank(houseTypeUrls))return;
		saveImg(user,projectHouseTypeId,projectCode,houseTypeUrls,"20");
	}
	
	private void saveImg(User user,Long projectId,String projectCode,String imgUrl,String type){
		if(StringUtils.isBlank(imgUrl))return;
		String[] urls=imgUrl.split(";");
		if(null==urls || urls.length<=0)return;
		for(int i=0;i<urls.length ;i++){
			ProjectImgDto projectImgDto=new ProjectImgDto();
			projectImgDto.setUserCode(user.getUserCode());
			projectImgDto.setMerchantId(user.getMerchantId());
			projectImgDto.setDelFlag("0");
			projectImgDto.setAccessCode(projectCode);
			projectImgDto.setLargeUrl(urls[i]);
			projectImgDto.setNormalUrl(urls[i]);
			projectImgDto.setSmallUrl(urls[i]);
			projectImgDto.setProjectImgType(type);
			projectImgDto.setProjectCode(projectCode);
			projectImgDto.setAccessCode(projectCode);
			projectImgDto.setProjectId(projectId);
			projectImgDto.setCreateUserId(user.getId());
			projectImgDto.setProjectImgCode("houseTypeCode");
			projectImgServiceFacade.save(projectImgDto);
		}
		
	}
	//查看
	@RequestMapping(value="view", method=RequestMethod.GET)
    public String  view(Long id,ModelMap map){
    	/*
    	 *1.判断权限 
    	 *2.调用查看接口
    	 *3.返回信息
    	*/
        if(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"estate:projectHouseType:view")){
        	try {
				Response<ProjectHouseType> response=projectHouseTypeServiceFacade.findById(id);
				if(response.isSuccess()){
					ProjectHouseType projectHouseType=response.getEntity();
					//设置位置信息
					String positionName="";
					String position=projectHouseType.getPosition();
					if(StringUtils.isNotBlank(position)){
						String[] positionCheck=position.split(",");
						for(int i=0;i<positionCheck.length;i++){
		    				if(i==0){
		    					positionName=PositionEnum.getByNo(positionCheck[i]).getDes();
		    				}else{
		    					positionName=positionName+",";
		    					positionName=positionName+PositionEnum.getByNo(positionCheck[i]).getDes();
		    				}
		    			}
					}
					
					projectHouseType.setPosition(positionName);
					map.put("projectHouseType", projectHouseType);
					ProjectImgDto dto = new ProjectImgDto();
					dto.setProjectId(response.getEntity().getId());
					dto.setProjectImgType("20");
					dto.setProjectImgCode("houseTypeCode");
					ResponseList<ProjectImg> list = projectImgServiceFacade.findByDto(dto);
					if(list.isSuccess()&&list.getEntity()!=null){
						map.put("houseTypeImgList", list.getEntity());
					}else{
						map.put("houseTypeImgList", new ArrayList<ProjectImg>());
					}
				}else {
					map.put("projectHouseType", new ProjectHouseType());
					map.put("houseTypeImgList", new ArrayList<ProjectImg>());
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				map.put("projectHouseType", new ProjectHouseType());
				map.put("houseTypeImgList", new ArrayList<ProjectImg>());
			}
        	return "/estate/projectHouseType/view";
    	}
        return Const.NO_AUTHORIZED_URL;
    }
	
	//查看
	 @RequestMapping(value="toEdit", method=RequestMethod.GET)
	 public String  toEdit(Long id,ModelMap map){
	    	/*
	    	 *1.判断权限 
	    	 *2.调用查看接口
	    	 *3.返回信息
	    	*/
	        if(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"estate:projectHouseType:edit")){
	        	try {
					Response<ProjectHouseType> response=projectHouseTypeServiceFacade.findById(id);
					if(response.isSuccess()){
						map.put("projectHouseType", response.getEntity());
						ProjectImgDto dto = new ProjectImgDto();
						dto.setProjectId(response.getEntity().getId());
						dto.setProjectImgType("20");
						dto.setProjectImgCode("houseTypeCode");
						ResponseList<ProjectImg> list = projectImgServiceFacade.findByDto(dto);
						if(list.isSuccess()&&list.getEntity()!=null){
							map.put("houseTypeImgList", list.getEntity());
						}else{
							map.put("houseTypeImgList", new ArrayList<ProjectImg>());
						}
					}else {
						map.put("projectHouseType", new ProjectHouseType());
						map.put("houseTypeImgList", new ArrayList<ProjectImg>());
					}
					map.put("positionEnum", PositionEnum.values());
				} catch (Exception e) {
					logger.error(e.toString(),e);
					map.put("projectHouseType", new ProjectHouseType());
					map.put("houseTypeImgList", new ArrayList<ProjectImg>());
				}
	        	return "/estate/projectHouseType/form";
	    	}
	        return Const.NO_AUTHORIZED_URL;
	    }
	
	//修改
	@RequestMapping(value="edit", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  edit(ProjectHouseTypeDto dto,HttpServletRequest request,String houseTypeUrls){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用修改接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"estate:projectHouseType:edit"))){
        	try {
        		String[] positionCheck=request.getParameterValues("positionCheck");
        		String position="";
        		if(null != positionCheck){
        			for(int i=0;i<positionCheck.length;i++){
        				if(i==0){
        					position=positionCheck[i];
        				}else{
        					position=","+positionCheck[i];
        				}
        			}
        		}
    			
        		dto.setPosition(position);
        		Response<Integer> response=projectHouseTypeServiceFacade.updateByPrimaryKey(dto, true);
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.UPDATE_SUCCEED);
					Response<Project> entity = projectServiceFacade.findById(dto.getProjectId());
					dto.setProjectCode(entity.getEntity().getProjectCode());
					saveProjectImg(ShiroUtil.getCurrentUser(),dto,houseTypeUrls);
				}else{
					ar.setFailMsg(Const.UPDATE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.UPDATE_FAIL);
			}
    	}
    	return ar;
    }
	
	//删除
	@RequestMapping(value="delete", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  delete(Long id){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用查看接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"estate:projectHouseType:delete"))){
        	try {
        		Response<Integer> response=projectHouseTypeServiceFacade.deleteByPrimaryKey(id);
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.DEL_SUCCEED);
				}else {
					ar.setFailMsg(Const.DEL_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DEL_FAIL);
			}
    	}
    	return ar;
    }
	
	
	
	//分页查询
	@RequestMapping(value="list", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  list(ProjectHouseTypeDto dto,Integer pageSize,Integer pageNum){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用分页查询接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"estate:projectHouseType:list"))){
        	try {
        		Page<ProjectHouseType> response=projectHouseTypeServiceFacade.findPageByDto(dto, PageUtil.begin(pageNum, pageSize),pageSize);
                if(response.getSuccess()){
                    if(null==response.getRows())response.setRows(new ArrayList<ProjectHouseType>());
                	response.setPageNumber(pageNum);
                	List<ProjectHouseTypeVo> list=new ArrayList<ProjectHouseTypeVo>();
                	for(ProjectHouseType pht : response.getRows()){
                		ProjectHouseTypeVo phtv=new ProjectHouseTypeVo();
                		phtv=BeanUtil.convert2T(phtv,pht);
                		//查询项目
                		Response<Project> responseProject=projectServiceFacade.findById(pht.getProjectId());
                		if(responseProject.isSuccess()){
                			phtv.setProjectName(responseProject.getEntity().getProjectName());
                		}
                		//查询是否有户型图
                		ProjectImgDto imgDto = new ProjectImgDto();
                		imgDto.setProjectId(pht.getId());
                		imgDto.setProjectImgType("20");
                		imgDto.setProjectImgCode("houseTypeCode");
                		ResponseList<ProjectImg> imgList = projectImgServiceFacade.findByDto(imgDto);
                		if(imgList.isSuccess()&&imgList.getEntity()!=null){
                			phtv.setHasImg("有");
                		}else{
                			phtv.setHasImg("无");
                		}
                		list.add(phtv);
                	}
                	Page<ProjectHouseTypeVo> pageaVo=new Page<ProjectHouseTypeVo>(response.getTotal(),list);
                	pageaVo.setPageNumber(pageNum);
                	pageaVo.setPageSize(pageSize);
                	ar.setSucceed(pageaVo);
                }else{
                	ar.setFailMsg(Const.DATA_FAIL);
                }
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
    	}
    	return ar;
    }
	

}
